const COLUMNS = [
	{prop:"id", label:"销售单号",width:"80"},
	{prop:"name", label:"公司名称",width:"150"},
	{prop:"legalperson", label:"法人",width:"70"},
	{prop:"phone", label:"电话",width:"110"},
	{prop:"weixin", label:"微信",width:"70"},
	{prop:"saletype", label:"类别",width:"50"},
	{prop:"src", label:"来源",width:"50"},
	{prop:"assignetype", label:"分配方式",width:"50"},
	{prop:"adddatetime", label:"添加日期",width:"120"},
	{prop:"updatetime", label:"跟踪日期",width:"120"},
	{prop:"enddatetime", label:"截止日期",width:"120"},
	{prop:"trackername", label:"跟踪者",width:"80"},
	{prop:"amount", label:"成交金额",width:"60"},
	{prop:"actualcollection", label:"实际收款",width:"60"},
	{prop:"status", label:"状态",width:"80"},
	{prop:"memo", label:"备注",width:"80"}	
]

let validate = {
    validatePass: (rule, value, callback) => {
        
    }
};

const mycusRules = {
    name: [
        {required: true, message: '请输入公司名称', trigger: 'blur'}
    ],
    phone: [
        {required: true, message: '请输入手机号', trigger: 'blur'}
    ]

};
const trackRules = {
    createtime: [
        {required: true, message: '请选择跟踪日期', trigger: 'blur'}
    ],
    content: [
        {required: true, message: '请输入跟踪内容', trigger: 'blur'}
    ]
};
transFormDetailRules = {
	name: [
	    {required: true, message: '请选择服务名称', trigger: 'blur'}
	],
	amount: [
	    {required: true, message: '请输入数量', trigger: 'blur'},
		constIntRule
	],
	totalprice: [
	    {required: true, message: '请输入服务金额', trigger: 'blur'},
		constIntRule
	]
}
transFormRecorderRules = {
	collectiondate: [
	    {required: true, message: '请输入收款日期', trigger: 'blur'}
	],
	loantype: [
	    {required: true, message: '请输入收款方式', trigger: 'blur'}
	],
	reciverid: [
	    {required: true, message: '请输入收款人', trigger: 'blur'}
	],
	totalprice: [
	    {required: true, message: '请输入收款金额', trigger: 'blur'}
	]
}
const transRules = {
	sellerid: [
        {required: true, message: '请选择销售人员', trigger: 'blur'}
    ],
	outformerid: [
	    {required: true, message: '请选择出单人', trigger: 'blur'}
	],
	handoverid: [
	    {required: true, message: '请选择交接人', trigger: 'blur'}
	],
	
	src: [
	    {required: true, message: '请选择来源', trigger: 'blur'}
	],
	
	signtype: [
	    {required: true, message: '请选择签约方式', trigger: 'blur'}
	],
	
    addresstype: [
        {required: true, message: '请选择地址类别', trigger: 'blur'}
    ],
    paytype: [
        {required: true, message: '请输入支付方式', trigger: 'blur'}
    ],
    business: [
        {required: true, message: '请输入办理业务', trigger: 'blur'}
    ],
    invoicingtype: [
        {required: true, message: '请选择开票类别', trigger: 'blur'}
    ],
    amountinvoicing: [
        {required: true, message: '请输入开票金额', trigger: 'blur'},
		constIntRule
    ],
    taxtype: [
        {required: true, message: '请输入选择税务类别', trigger: 'blur'}
    ],
   
    amounttotal: [
        {required: true, message: '请输入总计费用', trigger: 'blur'},
		constIntRule
    ],
    amountreceivables: [
        {required: true, message: '请输入应收费用', trigger: 'blur'},
		constIntRule
    ],
    amountpayin: [
        {required: true, message: '请输入实收费用', trigger: 'blur'},
		constIntRule
    ],
    amountend: [
        {required: true, message: '请输入尾款', trigger: 'blur'},
		constIntRule
    ],
    gifts: [
        {required: true, message: '请输入赠送情况', trigger: 'blur'}
    ],
    amountendcondition: [
        {required: true, message: '请输入尾款条件', trigger: 'blur'}
    ],
    receiverid: [
        {required: true, message: '请输入接收人', trigger: 'blur'}
    ],
	collectiondate: [
	    {required: true, message: '请输入收款日期', trigger: 'blur'}
	],
	transdate: [
	    {required: true, message: '请输入流转日期', trigger: 'blur'}
	],
	servicedate: [
	    {required: true, message: '请输入服务期限', trigger: 'blur'}
	],
	financeid: [
	    {required: true, message: '请输入财务', trigger: 'blur'}
	],
    supervisorid: [
        {required: true, message: '请输入主管', trigger: 'blur'}
    ],
	materials: [
		{required: true, message: '请输选择相关材料', trigger: 'blur'}
	]
};
let app = new Vue({
    el: "#app",
    data() {
        return {
			suffix:"",
        	leftbar_show:true,
			// 模式 捡漏和不捡漏
			//model:"不捡漏",
			// 添加、编辑标识
			action:"",
			index:0,
			dindex:0,
			rindex:0,
			tabvalue:'base',
			tableHeight:window.innerHeight - 180,
			tablecolums:COLUMNS,
			uploadurl:axios.defaults.baseURL + "api/transform/annex/upload/",
			// 上传收款截图
			uploadrecorderurl:axios.defaults.baseURL + "api/transformrecorder/annex/upload/",
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			tempfilelist:[],
			servicecolums:[
				{"prop":"name", "label":"名称","width":"100"},
				{"prop":"spec", "label":"规格","width":"80"},
				{"prop":"type", "label":"类别","width":"80"},
				{"prop":"amount", "label":"数量","width":"50"},
				{"prop":"unit", "label":"单位","width":"50"},
				{"prop":"price", "label":"单价","width":"100"},
				{"prop":"totalprice", "label":"服务金额","width":"100"},
				//{"prop":"cost", "label":"成本金额","width":"100"},
				{"prop":"items", "label":"服务项目","width":"80"},
				{"prop":"memo", "label":"备注","width":"80"}
			],
			detailcolums:[
				{"prop":"id", "label":"编号","width":"100"},
				{"prop":"name", "label":"名称","width":"100"},
				{"prop":"spec", "label":"规格","width":"80"},
				{"prop":"type", "label":"类别","width":"80"},
				{"prop":"unit", "label":"单位","width":"50"},
				{"prop":"price", "label":"单价","width":"100"},
				//{"prop":"totalprice", "label":"服务金额","width":"100"},
				//{"prop":"cost", "label":"成本金额","width":"100"},
				{"prop":"items", "label":"服务项目","width":"80"},
				{"prop":"memo", "label":"备注","width":"80"}
			],
			transformpayrecorder:[
				{"prop":"collectiondate", "label":"收款日期","width":"100"},
				{"prop":"totalprice", "label":"收款金额","width":"100"},
				{"prop":"reciver", "label":"收款人","width":"100"},
				{"prop":"loantype", "label":"收款类型","width":"100"},
				{"prop":"memo", "label":"备注","width":"150"}
			],
			dialogFormVisible:false,
			dialogTrackFormVisible:false,
			dialogTransFormVisible:false,
			downloadDialogVisible:false,
			dialogMoveFormVisible:false,
			dialogTypeFormVisible:false,
			dialogBatchFormVisible:false,
			dialogTransFormDetailVisible:false,
			transFormRecorderVisible:false,
			downloadUrl:"",
			submitDisable:false,
			checkboxDisable:true,
			// 当前优惠单
			discountform:{},
			queryForm:{
                userid: localStorage.getItem('USERID'),
                keyword: "",
                saletype: [],
				assignetype: [],
                src: [],
				signtype: [],
				weixin:[],
				tracker:[],
				status:[],
				outdate:"不捡漏",
				datetime:[],
				updatetime:[],
				founddate:[],
				pageNo:1, // 当前页码
				pagesize:100 ,// 每页记录数
				pagesizes:[10,20,50,100]
			},
			pagetotal:0,
			pickerOptions: {
			  shortcuts: [{
				text: '最近一周',
				onClick(picker) {
				  const end = new Date()
				  const start = new Date()
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
				  picker.$emit('pick', [start, end])
				}
			  }, {
				text: '最近一个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
				  picker.$emit('pick', [start, end]);
				}
			  }, {
				text: '最近三个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
				  picker.$emit('pick', [start, end]);
				}
			  }]
			},
            mycusForm: {
                id: null,
                name: "",
                legalperson: "",
				contacter:"",
                phone: "",
                address: "",
                area: "",
				saletype:"无",
				weixin:"未添加",
				src:"工商",
				signtype:"",
				trackerid:parseInt(localStorage.getItem('USERID')),
				trackername:localStorage.getItem('USERNAME'),
				status:"未签约",
				amount:"0",
				actualcollection:"0",
				balance:"0",
				balancecondtion:"",
				template:"",
				memo:""
            },
			mycusFormOrg: {
			},
			trackForm:{
				ids:[],
				datetime:"",
				trackerid:"",
				compname:"",
				tracktype:"电话沟通",
				tracktypes:["电话沟通"],
				template:"",
				content:""
			},
			moveForm:{
				cusIds:[],
				mycusIds:[],
				trackerid:parseInt(localStorage.getItem('USERID')),
				target:"公共客户"
			},
			outdateform:{
				mycusIds:[],
				cusIds:[],
				trackerid:parseInt(localStorage.getItem('USERID'))
			},
			typeForm:{
				cusIds:[],
				mycusIds:[],
				trackerid:parseInt(localStorage.getItem('USERID')),
				saletype:"A"
			},
			batchForm:{
				userid: localStorage.getItem('USERID'),
				founddate:[],
			},
            transForm: {
                id: null,
				mycustomerid:null,
				customerid:null,
                compname: "",
                legalperson: "",
				contacter:"",
                phone: "",
                address: "",
                area: "",
				status:"",
				business:"",
				collectiondate:"",
				transdate:"",
				treasurer:"",
				sellerid:"",
				sellername:"",
				outformerid:"",
				outformername:"",
				src:"",
				signtype:"",
				addresstype:"",
				invoicingtype:"",
				amountinvoicing:"",
				taxtype:"",
				gifts:"",
				paytype:"",
				service:[],
				// 收款记录
				recorder:[
				],
				amounttotal:0,
				amountreceivables:"",
				amountpayin:"",
				amountend:"",
				amountendcondition:"",
				financename:"",
				financestatus:"",
				materials:[],
				annex:[],
				handovername:"",
				handoverstatus:"",
				supervisor:"",
				financeid:"",
				handoverid:"",
				supervisorid:"",
				receiverid:"",
				costerid:"",
				discount_id:"",
				receivername:"",
				receiverstatus:"",
				supervisorname:"",
				supervisorstatus:"",
				costername:"",
				costerstatus:"",
				memo:""
				//oldprice:0,
				//newprice:0
            },
			transFormDetail:{
				id:0,
				serviceid:0,
				name:"",
				spec:"",
				type:"",
				amount:0,
				unit:"",
				cost:0,
				price:0,
				totalprice:0,
				memo:"",
				// 服务内容
				service:[
				]
			},
			transFormRecorder:{
				id:0,
				collectiondate:'',
				totalprice:0,
				loantype:'',
				reciver:'',
				reciverid:'',
				annex:[],
				memo:""
			},
			// 代理记账每年赠送月数上限
			countup: 0,
			// 代理记账每年收费金额上限
			amountup:0,
			// 代理记账单位月数
			number:0,
			// 来源
			sources:["线索","工商","渠道"],
			signtypes:["新签","续签","转介绍"],
			invoicingtypes:["增值税普通发票","增值税专用发票","不开票"],
			taxtypes:["小规模","小规模+票","一般纳税人","一般纳税人+票","个体","上门服务"],
			materialslist:["营业执照 正本原件/复印件","准予设立通知书","房产证 原件/复印件","租赁合同 原件/复印件","场地使用证明",
			"银行回单卡","基本存款信息表（开户许可证）原件/复印件","法人身份证原件/复印件","股东身份证原件/复印件","监事身份证原件/复印件","财务身份证原件/复印件",
			"公章","发票章","财务章","法人章","合同章","报税CA","UKEY","税控盘","空白发票","发票领购簿","财务报表 （资产负债表、现金流量表、利润表）","其他资料"],
			addresstypes:["自有地址","挂靠地址"],
			allstatus:["待审核","已审核","执行中","异常终止","到期续签","到期终止"],
			templates:["未接通","接通挂掉（在忙或者其他原因）","有财务没兴趣了解（有会计或代账公司）","有需求（无会计）","暂时无需求（还未到期）"],
			loantypes:['支付宝','微信','对公','现金'],
			areas:[],
			// 所有用户
			users:[],
			//按跟踪者查询
			members:[],
			//服务项目列表
			services :[],
			discount:{
				preferential_description:"",
				price:"",
				new_price:""
			},
			// 指定客户的优惠单
			discountlist:[],
			// 多选
			multipleSelection:[],
			pagedata:[],  // 当前页结果集
			loaded:false,
        }
    },
	methods: {
		// 显示侧边栏
		showLeftBar() {
			if (this.leftbar_show) {
				this.leftbar_show = false
			} else {
				this.leftbar_show = true
			}
		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 计算尾款
		compute_blance() {
			this.mycusForm.balance = this.mycusForm.amount-this.mycusForm.actualcollection
		},
		// 流转单对话框
		transFormDialogShow(index, row) {
			this.action="edit"
			this.index = index;
			this.transForm.id = row.id
			this.transForm.mycustomerid = row.id
			this.transForm.customerid = row.customerid
			this.transForm.compname = row.name
			this.transForm.legalperson = row.legalperson
			this.transForm.contacter = row.contacter
			this.transForm.phone = row.phone
			this.transForm.area = row.area
			this.transForm.src = row.src
			this.transForm.sellerid = row.trackerid
			this.transForm.paytype = "微信"
			this.transForm.addresstype = "自有地址"
			this.transForm.invoicingtype="增值税普通发票"
			this.transForm.amountinvoicing=0
			this.transForm.taxtype="小规模"
			this.transForm.gifts="无"
			this.transForm.service=[]
			this.transForm.recorder=[]
			this.transForm.amounttotal=0
			this.transForm.amountreceivables=0
			this.transForm.amountpayin=0
			this.transForm.amountend=0
			this.transForm.amountendcondition="无"
			this.transForm.materials = []
			this.transForm.annex=[]
			this.tempfilelist = []
			this.transForm.financeid=""
			this.transForm.handoverid=""
			this.transForm.supervisorid=""
			this.transForm.receiverid=""
			this.transForm.costerid=""
			this.transForm.discount_id=""
			//this.transForm.oldprice=0
			//this.transForm.newprice=0
			
			//取得优惠券
			this.getdiscountlist(row.customerid)
			// 取得最近一次被驳回的流转单信息
			this.setlasttransform(row.id)
			
			this.dialogTransFormVisible = true;

		},
		// 流转
		async transto() {
			this.submitDisable = true;
            this.$refs.transForm.validate(async valid => {
                if (valid){
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
					    if (this.transForm.status == '已驳回') {
					    // 驳回流转单
					        var list = []
                            for (var item of this.transForm.annex) {
                                list.push(item.name);
                            }

					        this.transForm.annex = list
					    } else {
					    // 新建流转单
                            // 特殊处理上传证件文件列表
                            this.transForm.annex = []
                            for (var item of this.tempfilelist) {
                                this.transForm.annex.push(item.name);
                            }
					    }
						let res = await axios.put('api/transform/add', this.transForm);
						if (res.code === 200) {
							this.$message.success(res.message);
							this.query();
							this.dialogTransFormVisible = false
						}else {
							this.$message.error(res.message);
						}
					}catch (e) {
						this.$message.error('流转单请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                } else {
					if (this.transForm.service.length ==0) {
						this.$message.error('请在办理业务中添加服务项目');
						this.tabvalue = 'business'
					} else if (this.transForm.materials.length ==0) {
						this.$message.error('请在上传材料中勾选相关材料');
						this.tabvalue = 'materials'
					} else if (this.tempfilelist.length ==0) {
						this.$message.error('请在上传材料中上传相关材料');
						this.tabvalue = 'materials'
					} else {
						this.$message.error('请确认基础信息、办理业务、上传材料*号项目都以填写。');
					}
				}
            })
			this.submitDisable = false;
		},
		trackOpen() {
			if (this.multipleSelection.length == 0) {
				this.$message.error('请选择数据行！');
				return;
			}
			this.trackForm.ids =[];
			for (let row of this.multipleSelection) {
				if (row.status == '已释放') {
					this.$message.error('不能选择已释放的数据行！');
					return;
				}
				if (row.status == '已签约') {
					this.$message.error('不能选择已面访或已签约的数据行！');
					return;
				}
				
				this.trackForm.ids.push(row.id)
			}
			this.dialogTrackFormVisible = true;
			this.trackForm.datetime = "";
			//this.trackForm.compname = row.name;
			//this.trackForm.trackerid = row.trackerid;
			this.trackForm.tracktype="电话沟通";
			this.trackForm.content="";
		},
		async trackSubmit() {
			this.submitDisable = true;
            this.$refs.trackForm.validate(async valid => {
                if (valid){
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.put('api/trackrecord/add', this.trackForm);
						if (res.code === 200) {
							this.query();
							this.dialogTrackFormVisible = false;
						}else {
							this.$message.error(res.message);
						}
					}catch (e) {
						this.$message.error('跟踪请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                }
            })	
			this.submitDisable = false;
		},
		// 当批量跟踪内容模板选择时
		trackchange(value) {
			this.trackForm.content = value
		},
		// 当备注模板选择时
		templatechange(value) {
			this.mycusForm.memo = value
		},
		// 当跟踪者ID变化时，跟踪者名称也变化
		trackerChange(value) {
			let obj = {};
			obj = this.users.find((item)=>{
			 return item.id === value;
			});
			this.mycusForm.trackername = obj.name;
		},
		
		// 优惠单ID变化时，价格也变化
		dicountChange(value) {
			this.discountform = this.discountlist.find((item)=>{
			 return item.id === value;
			});
		},

		// 检查数据是否有修改
		checkDataChanged() {
			res = [];
			// 比对数据有无发生变化
			for (let key in this.mycusForm) {
				if (this.mycusForm[key] != this.mycusFormOrg[key] && key != 'recs') {
					res.push({filedname:key,valueOrg: this.mycusFormOrg[key], valueChanged: this.mycusForm[key]});;
				}
			}
			return res;
		},
		// 确认
		async cofirm(){
			this.submitDisable = true;
            this.$refs.mycusForm.validate(async valid => {
                if (valid){
					if (this.mycusForm.status == '已签约') {
//						if (this.mycusForm.amount == '' || this.mycusForm.amount*1 <0) {
//							this.$message.error('请输入成交金额。');
//							return
//						}
						// if (this.mycusForm.actualcollection == '' || this.mycusForm.actualcollection*1 <=0) {
						// 	this.$message.error('请输入实际收款。');
						// 	return
						// }
						// if (this.mycusForm.amount != this.mycusForm.actualcollection && (this.mycusForm.balance == '' || this.mycusForm.balance*1 <0)) {
						// 	this.$message.error('请输入尾款金额。');
						// 	return
						// }
						// if (this.mycusForm.balance*1 > 0 && this.mycusForm.balancecondtion == '') {
						// 	this.$message.error('尾款条件不能为空。');
						// 	return
						// }
					}
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = null;
						if (this.action=="add") {
							res = await axios.put('api/mycus/add', this.mycusForm);
						} else{
							// 编辑
							checkdata = this.checkDataChanged();
							if (checkdata.length > 0) {
								this.mycusForm.recs = checkdata;
								res = await axios.put('api/mycus/update', this.mycusForm);
							} else {
								res = {code:400,message:"数据未变化"};
							}
						}
						if (res.code === 200) {
							this.query();
							this.dialogFormVisible = false
						}else {
							this.$message.error(res.message);
						}					

					}catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                }
            })
			this.submitDisable = false;
		},
		start(){
			//this.model = this.queryForm.outdate
			this.queryForm.pageNo = 1
			this.query()
		},
		// 查询
		async query() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/mycus/query', this.queryForm);
				if (res.code === 200) {
					this.pagedata = res.data;
					this.pagetotal = res.total;
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},
		
		handleRemove(file, filelist) {
			this.createTempfilelist(filelist);
		},
		handledownloadPreview(file) {
			//console.log(file)
			//this.suffix =file.response.data.mine
			//this.downloadUrl = file.response.data.url;
			//this.downloadDialogVisible = true;
		},
		handleAvatarSuccess(res, file, filelist) {
			this.createTempfilelist(filelist);
		},
		beforeAvatarUpload(file) {
		    const isLt20M = file.size / 1024 / 1024 < 20;
		    if (!isLt20M) {
		        this.$message.error('上传图片大小不能超过 20MB!');
		        return false;
		    }
		    return true;
		},	
		createTempfilelist(filelist) {
			console.log(filelist)
			this.tempfilelist = []
			for (let s of filelist) {
				if (typeof(s.response) != "undefined") {
					this.tempfilelist.push({
						name: s.response.data.name,
						url: ""
					});
				} else {
					this.tempfilelist.push({
						name: s.name,
						url: ""
					});
				}
			}	
			index = this.tempfilelist[0].name.lastIndexOf('.');
			this.tempfilelist[0].suffix = this.tempfilelist[0].name.substring(index+1);
	
			console.log(this.tempfilelist)
		},
		
		handledownloadPreview4annex(file) {
			//this.imgdialogImageUrl = file.url;
			//this.imgdialogVisible = true;
		},

		handleAvatarSuccess4annex(res, file, filelist) {
			this.transFormRecorder.annex = this.createAnnexfilelist(filelist);
		},
		
		createAnnexfilelist(filelist) {
			var tempfilelist = []
			for (let s of filelist) {
				if (typeof(s.response) != "undefined") {
					tempfilelist.push({
						name: s.response.data.name,
						url: s.response.data.url
					});
				} else {
					tempfilelist.push({
						name: s.name,
						url: s.url
					});
				}
			}
			return tempfilelist;
		},

		// 初始化团队成员列表
		async initMembers() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/team/member/' + localStorage.getItem('USERID'));
				if (res.code === 200) {
					this.members = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		// 打开添加区域对话框
		addAreaDailogOpen() {
			this.$prompt('请输入区域名称', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
			  inputErrorMessage: '区域名称不能为空'
			}).then(({ value }) => {
				this.areaSubmit(value);
			}).catch(() => {
				this.$message.error('区域添加请求出错！', value);
			});
		},
		async areaSubmit(value) {
			this.submitDisable = true;
			res = await axios.put('api/area/add/'+ value);
			if (res.code === 200) {
				this.initAreas();
			}else {
				this.$message.error(res.message);
			}
			this.submitDisable = false;
		},
		async initAreas() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/area/list');
				if (res.code === 200) {
					this.areas = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		// 取得所有用户列表
		async getAllUser() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/user/all');
				if (res.code === 200) {
					this.users = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		
		toolAction(acName) {
			if (acName == "添加") {
				this.add()
			} else if (acName == "批量添加") {
				this.showDialogBatchForm()
			} else if (acName == "转移") {
				this.movetoDialog()
			} else if (acName == "捡漏") {
				this.getOutdate()
			}else if (acName == "批量跟踪") {
				this.trackOpen()
			} else if (acName == "批量分类") {
				this.typetoDialog()
			}
		},
		selectionChange(selection){
			this.selection = selection
		},
		showDialogBatchForm() {
			this.dialogBatchFormVisible=true;
		},
		async addbatch() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				
				let res = await axios.put('api/mycus/addrandom', this.batchForm);
				if (res.code === 200) {
					this.query();
					this.$message.success(res.message);
					this.dialogBatchFormVisible=false;
				}else {
					this.$message.error(res.message);
				}
				
			}catch (e) {
				this.$message.error('批量添加请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},
		// 我的客户移动到公共客户或其他跟踪者
		movetoDialog() {
			this.moveForm.mycusIds =[];
			this.moveForm.cusIds = [];
			if (this.multipleSelection.length == 0) {
				this.$message.error('请选择数据行！');
				return;
			}
			for (let row of this.multipleSelection) {
				if (row.status == '已释放') {
					this.$message.error('不能选择已释放的数据行！');
					return;
				}
				
				this.moveForm.mycusIds.push(row.id)
				this.moveForm.cusIds.push(row.customerid)
			}
			this.dialogMoveFormVisible = true;

		},
		// // 我的客户移动到公共客户或其他跟踪者
		// movetoDialog() {
		// 	if (this.multipleSelection.length == 0) {
		// 		this.$message.error('请选择数据行！');
		// 		return;
		// 	}
		// 	this.dialogMoveFormVisible = true;
		// 	this.moveForm.mycusIds =[];
		// 	this.moveForm.cusIds = [];
		// 	for (let row of this.multipleSelection) {
		// 		this.moveForm.mycusIds.push(row.id)
		// 		this.moveForm.cusIds.push(row.customerid)
		// 	}

		// },
		// 客户释放到公共客户或转移给他人
		async moveto() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				if (this.moveForm.target == "跟踪者") {
					for (let row of this.multipleSelection) {
						if (row.trackerid == this.moveForm.trackerid ) {
							this.$message.error('不能将客户转移给自己！');
							return;
						}
					}
				}
				{
					let res = await axios.put('api/mycus/moveto', this.moveForm);
					if (res.code === 200) {
						this.query();
						this.$message.success(res.message);
						this.dialogMoveFormVisible = false;
					}else {
						this.$message.error(res.message);
					}
				}
			}catch (e) {
				this.$message.error('转移请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},
		//捡漏
		async getOutdate(){
		  try{
			this.$confirm('确认要将该过期客户重新加入我的客户吗?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  type: 'warning'
			}).then(async () => {
			  if (this.multipleSelection.length == 0) {
				this.$message.error('请选择数据行！');
				return;
			  }
			  	for (let row of this.multipleSelection) {
			  		if(row.status!="已过期" && row.status!="已释放"){
			  			this.$message.info('请选择已过期或已释客户');
			  			return;
			  		}		
			  	}
			  	this.outdateform.cusIds = [];
			  	this.outdateform.mycusIds = [];
			  	for (let row of this.multipleSelection) {
			  		this.outdateform.mycusIds.push(row.id)
			  		this.outdateform.cusIds.push(row.customerid)
			  	}
			  	let res = await axios.put('api/mycus/getoutdate', this.outdateform);
				if (res.code === 200) {
					this.$message.success(res.message);
					this.query();
				}else {
					this.$message.error(res.message);
				}
			  	
			}).catch(() => {
			  this.$message({
				type: 'info',
				message: '已取消'
			  });          
			});
		  }catch(e){
			this.$message.error('捡漏请求出错！', e.message);
		  }
		},
		// 我的客户批量分类
		typetoDialog() {
			this.typeForm.mycusIds =[];
			this.typeForm.cusIds = [];
			if (this.multipleSelection.length == 0) {
				this.$message.error('请选择数据行！');
				return;
			}
			for (let row of this.multipleSelection) {
				if (row.status == '已释放') {
					this.$message.error('不能选择已释放的数据行！');
					return;
				}
				this.typeForm.mycusIds.push(row.id)
				this.typeForm.cusIds.push(row.customerid)
			}
			this.dialogTypeFormVisible = true;

		},
		// 我的客户批量分类
		async typeto() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.put('api/mycus/typeto', this.typeForm);
				if (res.code === 200) {
					this.query();
					this.$message.success(res.message);
					this.dialogTypeFormVisible = false;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('批量分类请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},
		// 添加服务
		addService() {
			this.action="adddetail";
			this.dialogTransFormDetailVisible = true
			this.transFormDetail.id=0
			this.transFormDetail.serviceid=0
			this.transFormDetail.name=""
			this.transFormDetail.amount=0
			this.transFormDetail.unit=""
			this.transFormDetail.cost=0
			this.transFormDetail.price=0
			this.transFormDetail.totalprice=0
			this.transFormDetail.memo=""
			this.transFormDetail.service=[
			]
		},
		// 编辑服务
		editService(index, row) {
			this.action="editdetail"
			this.dindex = index;
			this.dialogTransFormDetailVisible = true
			this.transFormDetail = deepCopy(row)
		},
		// 删除服务
		delService(index, row){
			this.transForm.service.splice(index,1) 
		},
		// 添加收款记录
		addRecorder() {
			this.action="addrecorder";
			this.transFormRecorderVisible = true
			this.transFormRecorder.id=0
			this.transFormRecorder.collectiondate=""
			this.transFormRecorder.totalprice=0
			this.transFormRecorder.memo=""
			this.transFormRecorder.receiverid=""
			this.transFormRecorder.reciver =""
			this.transFormRecorder.annex=[
			]
		},
		// 编辑收款记录
		editRecorder(index, row) {
			this.action="editrecorder"
			this.rindex = index;
			this.transFormRecorder = deepCopy(row)
			this.transFormRecorderVisible = true
		},
		// 删除收款记录
		delRecorder(index, row){
			this.transForm.recorder.splice(index,1) 
		},
		// 确认添加，编辑服务信息
		confirmService() {
			this.$refs.transFormDetail.validate(async valid => {
				if (valid){
					var has = false; // 是否存在优惠项目
                    // 设定优惠单
                    this.dicountChange(this.transForm.discount_id);
					if(this.transForm.discount_id !=0 || this.transForm.discount_id !='') {
						for (let row of this.discountform.detail) {
							if (row.serviceid == this.transFormDetail.serviceid && row.servicedetailid == this.transFormDetail.id ) {
								has = true
								if (row.amount*1 == this.transFormDetail.amount*1 && row.pricea*1 == this.transFormDetail.totalprice*1) {
									continue
								} else {
									this.$message.error("服务项目,数量或价格与优惠单不符。" );
									return
								}
							}
						}
						if (has==false) { // 没有优惠项目时
							this.$message.error("优惠单项目与实际签约项目不符，请重新确认。" );
							return
						}
					} else {
						if (this.transFormDetail.name == '代理记账' ) {
							if (this.transFormDetail.amount <this.number) {
								this.$message.error("代理记账数量不能小于"+ this.number +"。");
								return;
							} else {
								// 如果不是12个月的倍数
								if (this.transFormDetail.amount%this.number!=0) {
									// 赠送的月数
									var month = this.transFormDetail.amount%this.number
									// 记账年数
									var year = Math.trunc (this.transFormDetail.amount/this.number)
									// 最大赠送月
									var max_month = year * this.countup
									if (month > max_month) {
										this.$message.error("代理记账每年赠送不能超过"+this.countup+"个月");
										return;
									}
									
								} 
								//判断是12个月的倍数，没有赠送
							    {
									// 每年上限金额
									var amountup = this.amountup
									// 记账年数
									var year = Math.trunc (this.transFormDetail.amount/this.number)
									var total = amountup * year
									if (this.transFormDetail.totalprice < total) {
										this.$message.error("服务金额不能小于"+ total+ "元。" );
										return;
									}
								}
							}
						} else {
							if (this.transFormDetail.amount <this.number) {
								this.$message.error("数量不能小于"+ this.number +"。");
								return;
							} else {
								// 如果不是周期数的倍数
								if (this.transFormDetail.amount%this.number!=0) {
									// 赠送的数量
									var month = this.transFormDetail.amount%this.number
									// 数量
									var year = Math.trunc (this.transFormDetail.amount/this.number)
									// 最大赠数量
									var max_month = year * this.countup
									if (month > max_month) {
										this.$message.error("服务每个周期赠送数量不能超过"+this.countup);
										return;
									}

								}
								//判断是周期数的倍数，没有赠送的情况
							    {
									// 周期上限金额
									var amountup = this.amountup
									// 数量
									var year = Math.trunc (this.transFormDetail.amount/this.number)
									var total = amountup * year
									if (this.transFormDetail.totalprice < total) {
										this.$message.error("服务金额不能小于"+ total+ "元。" );
										return;
									}
								}
							}

						}
					}

					let res = null;
					if(this.action=="adddetail") {
						// 判断服务是否已经添加
						//for (let row of this.transForm.service) {
						//	if (row.name == this.transFormDetail.name) {
						//		this.$message.error("您已添加过‘"+ this.transFormDetail.name +"’服务项目，无法重复添加。" );
						//		return
						//	}
						//}
						// 添加服务
						this.transForm.service.push(deepCopy(this.transFormDetail))
					} else if(this.action=="editdetail") {
						// 编辑服务
						this.transForm.service[this.dindex].name = this.transFormDetail.name
						this.transForm.service[this.dindex].unit = this.transFormDetail.unit
						this.transForm.service[this.dindex].time = this.transFormDetail.time
						this.transForm.service[this.dindex].cost = this.transFormDetail.cost
						this.transForm.service[this.dindex].price = this.transFormDetail.price
						this.transForm.service[this.dindex].memo = this.transFormDetail.memo
						this.transForm.service[this.dindex].totalprice = this.transFormDetail.totalprice
						this.transForm.service[this.dindex].amount = this.transFormDetail.amount
					}
					sum = 0
					for (let row of this.transForm.service) {
						sum = sum + row.price*1
					}
					this.transForm.amounttotal = sum
					this.dialogTransFormDetailVisible = false
				} else {
					
				}
			})			
		},
		// 确认添加，编辑收款记录
		confirmRecorder() {
			this.$refs.transFormRecorder.validate(async valid => {
				if (valid){
                    for (var item of this.users) {
                        if (item.id == this.transFormRecorder.reciverid) {
                            this.transFormRecorder.reciver = item.name
                        }
                    }
                    if(this.action=="addrecorder") {
						// 添加服务
						this.transForm.recorder.push(deepCopy(this.transFormRecorder))
					} else if(this.action=="editrecorder") {
						// 编辑服务
						this.transForm.recorder[this.rindex].totalprice = this.transFormRecorder.totalprice
						this.transForm.recorder[this.rindex].memo = this.transFormRecorder.memo
						this.transForm.recorder[this.rindex].collectiondate = this.transFormRecorder.collectiondate
						this.transForm.recorder[this.rindex].loantype = this.transFormRecorder.loantype
						this.transForm.recorder[this.rindex].reciverid = this.transFormRecorder.reciverid
						this.transForm.recorder[this.rindex].reciver = this.transFormRecorder.reciver
					}
					this.transFormRecorderVisible = false
				} else {
					
				}
			})			
		},
		// 添加
		add() {
			this.action="add";
			this.dialogFormVisible = true;
            this.mycusForm= {
                id: null,
                name: "",
                legalperson: "",
				contacter:"",
                phone: "",
                address: "",
                area: "",
				saletype:"无",
				weixin:"未添加",
				src:"工商",
				signtype:"",
				trackerid:parseInt(localStorage.getItem('USERID')),
				trackername:parseInt(localStorage.getItem('USERNAME')),
				status:"未签约",
				amount:0,
				actualcollection:0,
				balance:0,
				balancecondtion:"",
				memo:""
            }
		},
		// 编辑
		edit(index, row) {
			this.action="edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.mycusForm = deepCopy(row)
			// 保留原始数据，方便比对
			this.mycusFormOrg = deepCopy(row)
		},
		// 设定表格当前页
		handleCurrentPageChange (selectedPageNo) {
		  this.queryForm.pageNo = selectedPageNo
		  // 加载数据页
		  this.query()
		},
		//设定每页记录数
		handleSizeChange(val) {
			this.queryForm.pagesize = val
		  // 加载数据页
		  this.query()
	    },
		// 服务项目变化时
		async servicechange(id) {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				console.log(id)
				let res = await axios.get('api/servicedetail/get/' + id);
				if (res.code === 200) {
					this.transFormDetail.service = res.data;
					if (this.transFormDetail.service.length>0) {
						this.transFormDetail.amount = this.transFormDetail.service[0].number
						this.transFormDetail.serviceid = id
						this.transFormDetail.id = this.transFormDetail.service[0].id
						this.transFormDetail.name = this.transFormDetail.service[0].name
						this.transFormDetail.price = this.transFormDetail.service[0].price
						this.transFormDetail.totalprice = this.transFormDetail.service[0].price
						this.transFormDetail.unit = this.transFormDetail.service[0].unit
						this.transFormDetail.spec = this.transFormDetail.service[0].spec
						this.transFormDetail.type = this.transFormDetail.service[0].type
						
						this.transFormDetail.cost = this.transFormDetail.service[0].cost * this.transFormDetail.amount
						this.transFormDetail.items = this.transFormDetail.service[0].items 
						this.transFormDetail.memo = this.transFormDetail.service[0].memo
						
						// 设定
						// 代理记账每年赠送月数上限
						this.countup=this.transFormDetail.service[0].countup
						// 代理记账每年收费金额上限
						this.amountup=this.transFormDetail.service[0].amountup
						// 代理记账单位月数
						this.number = this.transFormDetail.service[0].number
						
					} 
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('服务项目请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		// 选择服务明细列表时
		serviceDetailClick(row, column, event) {
			this.transFormDetail.id = row.id
			this.transFormDetail.amount = row.number
			this.transFormDetail.name = row.name
			this.transFormDetail.price = row.price
			this.transFormDetail.totalprice = row.price
			this.transFormDetail.unit = row.unit
			this.transFormDetail.spec = row.spec
			this.transFormDetail.type = row.type
			this.transFormDetail.cost = row.cost
			this.transFormDetail.items = row.items
			this.transFormDetail.memo = row.memo
			
			// 设定
			// 代理记账每年赠送月数上限
			this.countup=row.countup
			// 代理记账每年收费金额上限
			this.amountup=row.amountup
			// 代理记账单位月数
			this.number = row.number
			
		},
		// 取得所有服务项目
		async getService() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/service/get');
				if (res.code === 200) {
					this.services = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('服务项目请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},	
		// 取得指定客户的优惠单
		async getdiscountlist(id) {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/discountlist/getlist/' + id);
				if (res.code === 200) {
					this.discountlist = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('服务项目请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},	
		// 取得最后一次驳回的流转单信息
		async setlasttransform(mycustomerid) {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/transform/getlast/' + mycustomerid);
				if (res.code === 200) {
					this.transForm = res.data;
				}else {
					//this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('驳回的流转单信息请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		outdateChange() {
			this.pagedata = [];
			this.pagetotal = 0;
		}
	},
	async mounted() {
		// 自动调整表格高度
		window.onresize = () => {
		  return (() => {
			this.tableHeight = window.innerHeight - 180
		  })()
		}
		
		//初始化用户列表
		this.getAllUser();
		// 取得查询条件跟踪者列表
		this.initMembers();
		// 初始化区域列表
		this.initAreas();
		// 取得服务列表
		this.getService();
		// 初始化我的客户列表
		// this.query();
	}

});	